import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AuthService } from '@/core/auth/auth.service';
import { delay, finalize, tap } from 'rxjs/operators';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
})
export class LoginComponent implements OnInit {
  loginForm!: FormGroup;
  loading: boolean = false;

  passwordVisible: boolean = false;

  constructor(
    public authSrv: AuthService,
    public router: Router,
    private notification: NzNotificationService,
    private message: NzMessageService,
    private fb: FormBuilder
  ) {}

  validateForm() {
    for (const key in this.loginForm.controls) {
      if (this.loginForm.controls.hasOwnProperty(key)) {
        this.loginForm.controls[key].markAsDirty();
        this.loginForm.controls[key].updateValueAndValidity();
      }
    }
    return this.loginForm.valid;
  }

  login(): void {
    if (this.validateForm()) {
      this.loading = true;
      this.authSrv
        .login(this.loginForm.value)
        .pipe(
          tap(() => {
            this.notification.success('登录成功', '2秒后跳转');
          }),
          delay(2000),
          finalize(() => {
            this.loading = false;
          })
        )
        .subscribe(
          () => {
            if (this.authSrv.redirectUrl) {
              this.router.navigateByUrl(this.authSrv.redirectUrl);
            } else {
              this.router.navigate(['dashboard']);
            }
          },
          (err: HttpErrorResponse) => {
            this.message.error(err.error);
          }
        );
    }
  }

  ngOnInit(): void {
    this.loginForm = this.fb.group({
      username: [null, Validators.required],
      password: [null, Validators.required],
    });
  }
}
